import { defineStore } from "pinia";
import api, { type User } from "@/api/api";
import { showCaptcha } from "@/utils/captcha";

export const useUserStore = defineStore("UserStore", {
    state() {
        return {
            user: null as User,
        };
    },
    actions: {
        setUser(user) {
            this.user = user;
        },
        async getUser(uid: string) {
            // 获取用户信息
            let res = await api.userInfo({ uid });
            // 成功
            if (res.status === 200) {
                this.user = res.data;
                return;
            }
            // 未登录或登录失效
            if (res.status === 401) {
                showCaptcha(async (verifyParam) => {
                    uid = localStorage.getItem("uid");
                    let res = await api.userVisitorLogin({ uid, verifyParam });
                    // 登录成功
                    if (res.status == 200) {
                        this.user = res.data;
                        localStorage.setItem("uid", this.user.uid);
                    }
                    return { captchaResult: res.status == 200 };
                });
            }
        },
    },
});
